package com.emergency.embackend.service.impl;



import com.emergency.embackend.entity.QuizHistory;
import com.emergency.embackend.entity.User;
import com.emergency.embackend.exception.EmException;
import com.emergency.embackend.mapper.QuizHistoryMapper;
import com.emergency.embackend.mapper.UserMapper;
import com.emergency.embackend.service.QuizHistoryService;
import com.emergency.embackend.vo.QuizSortVO;
import com.emergency.embackend.vo.QuizSuitVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author chddd
 * @description
 * @create 2024/3/13 19:13:28
 */
@Service
public class QuizHistoryServiceImpl implements QuizHistoryService {
    @Autowired
    private QuizHistoryMapper quizHistoryMapper;
    @Autowired
    private UserMapper userMapper;

    @Override
    public void insert(QuizHistory quizHistory) {
        quizHistoryMapper.insert(quizHistory);
    }

    @Override
    public List<QuizSortVO> getSort() {
      List<QuizSortVO> sortResult = quizHistoryMapper.getSort(new Date());
      if(sortResult == null || sortResult.size()==0){
          throw new EmException("401","数据获取异常");
      }
        List<Long> ids = sortResult.stream().map(QuizSortVO::getUserId).collect(Collectors.toList());
        List<User> userList = userMapper.getUserList(ids);
        Map<Long, User> map = new HashMap<>(userList.size());
        userList.forEach(e->{
            map.put(e.getId(),e);
        });
        sortResult.forEach(sort->{
            sort.setNickName(map.get(sort.getUserId()).getNickName());
            sort.setIcon(map.get(sort.getUserId()).getIcon());
        });
        return sortResult;
    }

    @Override
    public List<QuizSuitVO> getHistory(Long userId) {
        List<QuizSuitVO> resList = quizHistoryMapper.getHistory(userId);
        if(resList != null && resList.size()!=0){
            return resList;
        }
        return null;
    }
}
